<template>
  <view class="statistics-container">
    <!-- 时间选择器 -->
    <view class="time-selector">
      <scroll-view class="time-tabs" scroll-x>
        <view class="tabs-list">
          <view 
            class="tab-item"
            :class="{ active: currentTimeRange === item.value }"
            v-for="item in timeRanges"
            :key="item.value"
            @click="handleTimeRangeChange(item.value)"
          >
            <text class="tab-text">{{ item.label }}</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 自定义时间选择 -->
      <view class="custom-time" v-if="currentTimeRange === 'custom'">
        <uni-datetime-picker 
          v-model="customStartTime" 
          type="date"
          placeholder="开始日期"
          @change="handleCustomTimeChange"
        />
        <text class="time-separator">至</text>
        <uni-datetime-picker 
          v-model="customEndTime" 
          type="date"
          placeholder="结束日期"
          @change="handleCustomTimeChange"
        />
      </view>
    </view>

    <scroll-view class="content-scroll" scroll-y refresher-enabled :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
      <view class="content">
        <!-- 关键指标卡片 -->
        <view class="metrics-section">
          <view class="metrics-grid">
            <view class="metric-card" v-for="metric in keyMetrics" :key="metric.key">
              <view class="metric-icon">
                <uni-icons :type="metric.icon" size="24" :color="metric.color" />
              </view>
              <view class="metric-info">
                <text class="metric-value">{{ metric.value }}</text>
                <text class="metric-label">{{ metric.label }}</text>
              </view>
              <view class="metric-trend" v-if="metric.trend">
                <uni-icons 
                  :type="metric.trend > 0 ? 'up' : 'down'" 
                  size="12" 
                  :color="metric.trend > 0 ? '#52C41A' : '#FF4D4F'" 
                />
                <text class="trend-text" :style="{ color: metric.trend > 0 ? '#52C41A' : '#FF4D4F' }">
                  {{ Math.abs(metric.trend) }}%
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 销售趋势图表 -->
        <view class="chart-section">
          <view class="section-header">
            <text class="section-title">销售趋势</text>
            <view class="chart-actions">
              <button class="chart-btn" :class="{ active: chartType === 'sales' }" @click="chartType = 'sales'">
                销售额
              </button>
              <button class="chart-btn" :class="{ active: chartType === 'orders' }" @click="chartType = 'orders'">
                订单量
              </button>
            </view>
          </view>
          <view class="chart-container">
            <view class="chart-placeholder" v-if="!chartData.length">
              <uni-icons type="bars" size="48" color="#ddd" />
              <text class="placeholder-text">暂无数据</text>
            </view>
            <view class="simple-chart" v-else>
              <!-- 简单的柱状图实现 -->
              <view class="chart-bars">
                <view 
                  class="chart-bar"
                  v-for="(item, index) in chartData"
                  :key="index"
                  :style="{ height: getBarHeight(item.value) + '%' }"
                >
                  <view class="bar-value">{{ formatChartValue(item.value) }}</view>
                </view>
              </view>
              <view class="chart-labels">
                <text 
                  class="chart-label"
                  v-for="(item, index) in chartData"
                  :key="index"
                >
                  {{ item.label }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 活动排行 -->
        <view class="ranking-section">
          <view class="section-header">
            <text class="section-title">活动排行</text>
            <view class="ranking-tabs">
              <button class="ranking-btn" :class="{ active: rankingType === 'sales' }" @click="rankingType = 'sales'">
                销售额
              </button>
              <button class="ranking-btn" :class="{ active: rankingType === 'orders' }" @click="rankingType = 'orders'">
                订单量
              </button>
            </view>
          </view>
          <view class="ranking-list">
            <view class="ranking-item" v-for="(item, index) in rankingData" :key="index">
              <view class="ranking-number" :class="{ top: index < 3 }">
                {{ index + 1 }}
              </view>
              <view class="ranking-info">
                <text class="activity-name">{{ item.name }}</text>
                <text class="activity-value">{{ formatRankingValue(item.value) }}</text>
              </view>
              <view class="ranking-progress">
                <view class="progress-bar" :style="{ width: getProgressWidth(item.value) + '%' }"></view>
              </view>
            </view>
          </view>
        </view>

        <!-- 数据概览 -->
        <view class="overview-section">
          <view class="section-header">
            <text class="section-title">数据概览</text>
          </view>
          <view class="overview-grid">
            <view class="overview-item" v-for="item in overviewData" :key="item.key">
              <text class="overview-label">{{ item.label }}</text>
              <text class="overview-value">{{ item.value }}</text>
              <text class="overview-desc">{{ item.desc }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { statisticsApi } from '@/api/groupbuy';

// 响应式数据
const refreshing = ref(false);
const currentTimeRange = ref('today');
const customStartTime = ref('');
const customEndTime = ref('');
const chartType = ref('sales');
const rankingType = ref('sales');

// 时间范围选项
const timeRanges = ref([
  { label: '今日', value: 'today' },
  { label: '昨日', value: 'yesterday' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '自定义', value: 'custom' },
]);

// 关键指标数据
const keyMetrics = ref([
  {
    key: 'totalSales',
    label: '总销售额',
    value: '¥0.00',
    icon: 'wallet',
    color: '#1890FF',
    trend: 0,
  },
  {
    key: 'totalOrders',
    label: '总订单数',
    value: '0',
    icon: 'list',
    color: '#52C41A',
    trend: 0,
  },
  {
    key: 'totalUsers',
    label: '参与用户',
    value: '0',
    icon: 'person',
    color: '#FA8C16',
    trend: 0,
  },
  {
    key: 'avgOrderValue',
    label: '客单价',
    value: '¥0.00',
    icon: 'star',
    color: '#722ED1',
    trend: 0,
  },
]);

// 图表数据
const chartData = ref<Array<{ label: string; value: number }>>([]);

// 排行数据
const rankingData = ref<Array<{ name: string; value: number }>>([]);

// 概览数据
const overviewData = ref([
  { key: 'conversionRate', label: '转化率', value: '0%', desc: '访问转化为订单的比例' },
  { key: 'repeatRate', label: '复购率', value: '0%', desc: '用户重复购买的比例' },
  { key: 'avgGroupSize', label: '平均团购人数', value: '0人', desc: '每个团购的平均参与人数' },
  { key: 'successRate', label: '成团率', value: '0%', desc: '成功成团的比例' },
]);

// 计算图表柱状图高度
const getBarHeight = (value: number) => {
  if (!chartData.value.length) return 0;
  const maxValue = Math.max(...chartData.value.map(item => item.value));
  return maxValue > 0 ? (value / maxValue) * 100 : 0;
};

// 格式化图表数值
const formatChartValue = (value: number) => {
  if (chartType.value === 'sales') {
    return `¥${(value / 100).toFixed(0)}`;
  }
  return value.toString();
};

// 格式化排行数值
const formatRankingValue = (value: number) => {
  if (rankingType.value === 'sales') {
    return `¥${(value / 100).toFixed(2)}`;
  }
  return `${value}单`;
};

// 计算进度条宽度
const getProgressWidth = (value: number) => {
  if (!rankingData.value.length) return 0;
  const maxValue = Math.max(...rankingData.value.map(item => item.value));
  return maxValue > 0 ? (value / maxValue) * 100 : 0;
};

// 获取时间范围参数
const getTimeRangeParams = () => {
  const now = new Date();
  let startTime = '';
  let endTime = '';

  switch (currentTimeRange.value) {
    case 'today':
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString();
      break;
    case 'yesterday':
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1).toISOString();
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
      break;
    case 'week':
      const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay());
      startTime = weekStart.toISOString();
      endTime = new Date(weekStart.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString();
      break;
    case 'month':
      startTime = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
      endTime = new Date(now.getFullYear(), now.getMonth() + 1, 1).toISOString();
      break;
    case 'custom':
      if (customStartTime.value && customEndTime.value) {
        startTime = new Date(customStartTime.value).toISOString();
        endTime = new Date(customEndTime.value + ' 23:59:59').toISOString();
      }
      break;
  }

  return { startTime, endTime };
};

// 加载统计数据
const loadStatisticsData = async () => {
  try {
    const { startTime, endTime } = getTimeRangeParams();
    
    // 加载关键指标
    const metricsRes = await statisticsApi.getData({ startTime, endTime });
    if (metricsRes.success) {
      const data = metricsRes.data;
      keyMetrics.value[0].value = `¥${(data.totalRevenue / 100).toFixed(2)}`;
      keyMetrics.value[1].value = data.totalOrders.toString();
      keyMetrics.value[2].value = data.totalUsers?.toString() || '0';
      keyMetrics.value[3].value = `¥${((data.totalRevenue / data.totalOrders || 0) / 100).toFixed(2)}`;
    }

    // 加载趋势数据
    const trendRes = await statisticsApi.getTrend({ 
      startTime, 
      endTime, 
      type: chartType.value 
    });
    if (trendRes.success) {
      chartData.value = trendRes.data.map((item: any) => ({
        label: item.date,
        value: item.value,
      }));
    }

    // 模拟排行数据
    rankingData.value = [
      { name: '团购活动A', value: 150000 },
      { name: '团购活动B', value: 120000 },
      { name: '团购活动C', value: 98000 },
      { name: '团购活动D', value: 85000 },
      { name: '团购活动E', value: 72000 },
    ];

    // 模拟概览数据
    overviewData.value = [
      { key: 'conversionRate', label: '转化率', value: '12.5%', desc: '访问转化为订单的比例' },
      { key: 'repeatRate', label: '复购率', value: '28.3%', desc: '用户重复购买的比例' },
      { key: 'avgGroupSize', label: '平均团购人数', value: '3.2人', desc: '每个团购的平均参与人数' },
      { key: 'successRate', label: '成团率', value: '85.7%', desc: '成功成团的比例' },
    ];

  } catch (error) {
    console.error('加载统计数据失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  }
};

// 时间范围变化
const handleTimeRangeChange = (value: string) => {
  currentTimeRange.value = value;
  if (value !== 'custom') {
    loadStatisticsData();
  }
};

// 自定义时间变化
const handleCustomTimeChange = () => {
  if (customStartTime.value && customEndTime.value) {
    loadStatisticsData();
  }
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  loadStatisticsData().finally(() => {
    refreshing.value = false;
  });
};

// 监听图表类型变化
watch(chartType, () => {
  loadStatisticsData();
});

// 监听排行类型变化
watch(rankingType, () => {
  // 这里可以重新加载排行数据
});

// 页面加载
onMounted(() => {
  loadStatisticsData();
});
</script>

<style lang="scss" scoped>
.statistics-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.time-selector {
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .time-tabs {
    white-space: nowrap;
    
    .tabs-list {
      display: flex;
      padding: 0 32rpx;
      
      .tab-item {
        flex-shrink: 0;
        padding: 24rpx 32rpx;
        position: relative;
        
        &.active {
          .tab-text {
            color: #1890FF;
            font-weight: 600;
          }
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background: #1890FF;
            border-radius: 2rpx;
          }
        }
        
        .tab-text {
          font-size: 28rpx;
          color: #666;
        }
      }
    }
  }
  
  .custom-time {
    display: flex;
    align-items: center;
    padding: 16rpx 32rpx;
    gap: 16rpx;
    
    .time-separator {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.content-scroll {
  flex: 1;
}

.content {
  padding: 24rpx 32rpx;
}

.metrics-section {
  margin-bottom: 32rpx;
  
  .metrics-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16rpx;
    
    .metric-card {
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx;
      display: flex;
      align-items: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      
      .metric-icon {
        margin-right: 16rpx;
      }
      
      .metric-info {
        flex: 1;
        
        .metric-value {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 4rpx;
        }
        
        .metric-label {
          font-size: 22rpx;
          color: #999;
        }
      }
      
      .metric-trend {
        display: flex;
        align-items: center;
        gap: 4rpx;
        
        .trend-text {
          font-size: 20rpx;
        }
      }
    }
  }
}

.chart-section,
.ranking-section,
.overview-section {
  margin-bottom: 32rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .chart-actions,
    .ranking-tabs {
      display: flex;
      gap: 8rpx;
      
      .chart-btn,
      .ranking-btn {
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
        font-size: 24rpx;
        border: 1rpx solid #ddd;
        background: #fff;
        color: #666;
        
        &.active {
          background: #1890FF;
          color: #fff;
          border-color: #1890FF;
        }
      }
    }
  }
}

.chart-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .chart-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400rpx;
    
    .placeholder-text {
      font-size: 24rpx;
      color: #999;
      margin-top: 16rpx;
    }
  }
  
  .simple-chart {
    .chart-bars {
      display: flex;
      align-items: end;
      height: 300rpx;
      gap: 8rpx;
      margin-bottom: 16rpx;
      
      .chart-bar {
        flex: 1;
        background: linear-gradient(180deg, #1890FF 0%, #40A9FF 100%);
        border-radius: 4rpx 4rpx 0 0;
        position: relative;
        min-height: 20rpx;
        
        .bar-value {
          position: absolute;
          top: -32rpx;
          left: 50%;
          transform: translateX(-50%);
          font-size: 20rpx;
          color: #666;
          white-space: nowrap;
        }
      }
    }
    
    .chart-labels {
      display: flex;
      gap: 8rpx;
      
      .chart-label {
        flex: 1;
        text-align: center;
        font-size: 20rpx;
        color: #999;
      }
    }
  }
}

.ranking-list {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .ranking-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .ranking-number {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      background: #f5f5f5;
      color: #999;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      font-weight: 600;
      margin-right: 16rpx;
      
      &.top {
        background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
        color: #fff;
      }
    }
    
    .ranking-info {
      flex: 1;
      margin-right: 16rpx;
      
      .activity-name {
        font-size: 28rpx;
        color: #333;
        display: block;
        margin-bottom: 4rpx;
      }
      
      .activity-value {
        font-size: 24rpx;
        color: #1890FF;
        font-weight: 600;
      }
    }
    
    .ranking-progress {
      width: 120rpx;
      height: 8rpx;
      background: #f0f0f0;
      border-radius: 4rpx;
      overflow: hidden;
      
      .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, #1890FF 0%, #40A9FF 100%);
        border-radius: 4rpx;
        transition: width 0.3s ease;
      }
    }
  }
}

.overview-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16rpx;
  
  .overview-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    text-align: center;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .overview-label {
      font-size: 24rpx;
      color: #999;
      display: block;
      margin-bottom: 8rpx;
    }
    
    .overview-value {
      font-size: 32rpx;
      font-weight: 600;
      color: #1890FF;
      display: block;
      margin-bottom: 8rpx;
    }
    
    .overview-desc {
      font-size: 20rpx;
      color: #ccc;
      line-height: 1.4;
    }
  }
}
</style>